import os
import time
system_home = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]
import spur
from config import config

log = open("/home/agentmanager/SDNST/log/getMsg.log", 'w')

def _call_test(test_script, cmd):
    # Build Config and default command
    cfg = {'controllers': [(config.controller_addr,6633)],
           'topo_discovery': config.topo_discovery_delay,
           'fail_mode': config.mininet_fail_mode}
    if cmd == None:
        cmd = [{'cmd': 'basic'}]
    print(cfg)
    ts = time.time()
    res = None
    exec_res = None
    shell = spur.SshShell(hostname=config.mininet_addr, username=config.mininet_user ,password=config.mininet_passwd
                          ,missing_host_key=spur.ssh.MissingHostKey.accept, private_key_file=config.vm_ssh_key)
    log.write("Starting Test: " + test_script + "\n")
    log.write("Test Config: %s\n" % cfg)
    for c in cmd:
        log.write("Test Command: %s\n" % c)
    log.flush()
    try:
        proc = shell.spawn(["/bin/bash", "-i", "-c", test_script])
        log.write("proc = shell....")
        proc.stdin_write("%s\n" % repr(cfg))
        for c in cmd:
            proc.stdin_write("%s\n" % repr(c))
        exec_res = proc.wait_for_result()
        res = eval(exec_res.output)
    except Exception as e:
        print e
        log.write("_call_test Exception: " + str(e) + "\n")
        log.flush()
        return [None, None]
    if config.enable_stat:
        log.write('[timer] Do all tests: %f sec.\n' % (time.time() - ts))
    return [res, exec_res.stderr_output]

if __name__=="__main__":
    cmd = [{'cmd':'tunnel','h1':1,'h2':3,'filter':'lldp'},{'cmd':'basic'}]
    res, test_std_err = _call_test(
        config.coord_test_case, cmd)

    # print isinstance(res,str)
    # print isinstance(test_std_err,str)
    print "==========================="
    log.write(str(res))
    print "-----------------------------------"
    log.write(test_std_err)